#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/wait.h>

int main()
{
    int fds[2] = {0};
    int n = pipe(fds);
    if (n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    std::cout << "pipe ok" << std::endl;

    pid_t id = fork();
    if (id < 0)
    {
        std::cerr << "fork error" << std::endl;
        return 2;
    }
    else if (id == 0)
    {
        // 子进程
        close(fds[0]);

        int cnt = 0;
        while (true)
        {
            std::string message = "child process:";
            message += std::to_string(getpid());
            message += ",";
            message += std::to_string(cnt);

            ::write(fds[1], message.c_str(), message.size());

            sleep(1);
            cnt++;
        }

        exit(0);
    }
    else
    {
        // 父进程
        close(fds[1]);

        char str[1024] = {0};
        while (true)
        {
            ssize_t n = ::read(fds[0], str, 1024);
            if (n > 0)
            {
                str[n] = 0;
                std::cout << str << std::endl;
            }
        }

        pid_t rid = waitpid(id, nullptr, 0);
        std::cout << "father wait child success: " << rid << std::endl;
    }

    return 0;
}